<!--
 * @Descripttion: 设备推移图
 * @LastEditors: xzh
 * @LastEditTime: 2023-11-21 21:52:55
-->
<template>
  <DileChart
    v-if="Object.keys(trendChartParam.chartData).length > 0"
    ref="chartRef"
    :loading="trendChartParam.loading"
    :chart="trendChartParam.chartData"
  />
  <DileEmpty v-else />
</template>

<script setup lang="ts">
import { ref, reactive, toRefs, nextTick } from "vue";
import { object_Inf } from "@/utils/typings/index.type";
import {
  produceDataTypeEnum,
  produceDataTypeMap,
  chartFiel_Y,
} from "../index.type";
import { dayjs } from "element-plus";
import DileChart from "@/components/dile-chart/index.vue";
import DileEmpty from "@/components/dile-empty/index.vue";
import Dile_Methods from "@/utils/methods";
import Dile_APi from "@/api";
import Dile_StoreAction from "@/utils/cache/store";
import ProduceDashboardUtils from "../utils";

let defaultData = () => ({
  loading: false,
  isAll: false,
  equipInfo: {},
  chartData: {},
  dataType: "",
});

/**
 * @Author: xzh
 * @Descripttion: 推移图参数
 * @Param:
 */
let trendChartParam = reactive<object_Inf>(defaultData());

/**
 * @Author: xzh
 * @Descripttion: 图表x/y轴字段key
 * @Param:
 */
let chartxAxis = {
  //AOi
  [produceDataTypeEnum.aoi]: "checkDate",
  [produceDataTypeEnum.aoiDefectRate]: "checkDate",
  [produceDataTypeEnum.aoiTestNum]: "checkDate",
};
/**
 * @Author: xzh
 * @Descripttion: 图表数据
 * @Param:
 */
let chartRef = ref<object_Inf>({});
/**
 * @Author: xzh
 * @Descripttion: 初始化
 * @Param:
 */
let init = (param: object_Inf) => {
  Object.assign(trendChartParam, defaultData(), {
    ...param,
  });
  //加载图表信息
  initChartData();
};

/**
 * @Author: xzh
 * @Descripttion: 加载图表数据源
 * @Param:
 * @param {*} id
 */
let initChartData = async () => {
  let { loading, equipInfo, dataType, dateValue, isAll } =
      toRefs(trendChartParam),
    [startDate, endDate] = dateValue.value.map((x: any) =>
      dayjs(x).format("YYYY-MM-DD")
    ),
    { equipmentCode } = equipInfo.value || {},
    //获取当前工厂
    { id } = Dile_StoreAction.getCurrentFactory(),
    api: string = "";
  try {
    loading.value = true;
    switch (dataType.value) {
      //AOI
      case produceDataTypeEnum.aoi:
      case produceDataTypeEnum.aoiTestNum:
      case produceDataTypeEnum.aoiDefectRate:
        api = !!isAll.value
          ? "getProducetAllAOITrendChart"
          : "getProducetAOITrendChart";
        break;
      //产出数
      case produceDataTypeEnum.formingOutput:
      case produceDataTypeEnum.cutEdgeOutput:
      case produceDataTypeEnum.stackingOutput:
        api = !!isAll.value
          ? "getProducetAllOutputTrendChart"
          : "getProducetOutputTrendChart";
        break;
      //稼动率
      case produceDataTypeEnum.formingUtilization:
      case produceDataTypeEnum.cutEdgeUtilization:
      case produceDataTypeEnum.aoiUtilization:
        api = !!isAll.value
          ? "getProducetAllUtilizeRateTrendChart"
          : "getProducetUtilizeRateTrendChart";
        break;
      //使用率
      case produceDataTypeEnum.formingUseRate:
        api = !!isAll.value
          ? "getProducetAllUseRateTrendChart"
          : "getProducetUseRateTrendChart";
        break;
    }
    let data = await Dile_APi[api]({
      startDate,
      endDate,
      equipmentCode,
      orgId: id,
      type: produceDataTypeMap[dataType.value],
    });
    //渲染图表
    data.length > 0 && initChartInfo(data);
  } finally {
    loading.value = false;
  }
};
/**
 * @Author: xzh
 * @Descripttion:渲染图表
 * @Param:
 * @param {*} data
 */
let initChartInfo = async (data: Array<object_Inf>) => {
  let { chartData, dataType, isAll } = toRefs(trendChartParam);
  //获取图表类型x/y轴字段
  let xAxis = chartxAxis[dataType.value] || "date";

  let dataArr = !isAll.value
    ? [
        {
          equipmentName: "",
          dataList: data,
        },
      ]
    : data;
  //获取x轴数据源
  let xAxisData = [
    ...new Set(
      dataArr
        .map((x) => x.dataList)
        .flat()
        .map((x) => dayjs(x[xAxis]).format("YYYY-MM-DD"))
        .sort((x, y) => dayjs(x).valueOf() - dayjs(y).valueOf())
    ),
  ];

  // 格式化图表内容
  chartData.value = {
    id: Dile_Methods.newGuid(),
    option: {
      xAxis: {
        type: "category",
        data: xAxisData,
      },
      yAxis: {
        type: "value",
        axisLabel: {
          formatter: `{value}${
            !!ProduceDashboardUtils.isDecimals(dataType.value) ? "%" : ""
          }`,
        },
      },
      tooltip: {
        trigger: "axis",
      },
      series: dataArr.map(({ equipmentName, dataList }) => {
        return {
          name: equipmentName,
          data: xAxisData.map((xData: string) => {
            let item =
              dataList.find(
                (x: object_Inf) => dayjs(x[xAxis]).format("YYYY-MM-DD") == xData
              ) || {};
            return item[chartFiel_Y[dataType.value]] || 0;
          }),
          label: {
            show: true,
            formatter: ({ value }: object_Inf) => {
              return !!ProduceDashboardUtils.isDecimals(dataType.value)
                ? `${value}%`
                : Dile_Methods.toThousands(value);
            },
          },
          type: "line",
        };
      }),
      dataZoom: [
        {
          type: "inside",
        },
        {
          type: "slider",
          height: 13, // 横条高度
          moveHandleSize: 0,
          selectedDataBackground: {
            lineStyle: {
              opacity: 0,
              color: "#e7efff",
            },
            areaStyle: {
              opacity: 0,
            },
          },
          handleIcon:
            "M-292,322.2c-3.2,0-6.4-0.6-9.3-1.9c-2.9-1.2-5.4-2.9-7.6-5.1s-3.9-4.8-5.1-7.6c-1.3-3-1.9-6.1-1.9-9.3c0-3.2,0.6-6.4,1.9-9.3c1.2-2.9,2.9-5.4,5.1-7.6s4.8-3.9,7.6-5.1c3-1.3,6.1-1.9,9.3-1.9c3.2,0,6.4,0.6,9.3,1.9c2.9,1.2,5.4,2.9,7.6,5.1s3.9,4.8,5.1,7.6c1.3,3,1.9,6.1,1.9,9.3c0,3.2-0.6,6.4-1.9,9.3c-1.2,2.9-2.9,5.4-5.1,7.6s-4.8,3.9-7.6,5.1C-285.6,321.5-288.8,322.2-292,322.2z",
        },
      ],
    },
  };
  await nextTick();
  //渲染图表
  chartRef.value.init();
};

defineExpose({
  init,
});
</script>
<style lang="scss" scoped>
.lineChart-container {
  height: 100%;
  width: 100%;
}
</style>
